//
//  CampusPreviewQuesionListController.m
//  ShowYork
//
//  Created by hxh on 2021/3/26.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "CampusPreviewQuesionListController.h"
#import "CampusQuetionItemCell.h"
#import "CampusPostQuestionViewController.h"
#import "CampusQuestionDetailViewController.h"
#import "CampusSchoolQuestionItemModel.h"
#import "CampusQuestionDetailModel.h"
@interface CampusPreviewQuesionListController ()<UITableViewDelegate,UITableViewDataSource,CampusQuetionItemCellDelelgate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,assign)NSInteger pageIndex;
@property (nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation CampusPreviewQuesionListController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
    
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
    
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;

}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    [self registNote];
    
    // Do any additional setup after loading the view.
}

- (void)setUI{
    self.navigationItem.title = @"问一问";
    UIButton *btn = [[UIButton alloc]init];
    [btn setTitle:@"发起提问" forState:UIControlStateNormal];
    [btn setTitleColor:RGBA(58, 58, 58, 1) forState:UIControlStateNormal];
    btn.titleLabel.font = font(12);
    [btn addTarget:self action:@selector(postMethod) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.pageIndex = 1;
    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf loadDataSource];
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf loadDataSource];
    }];

    
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.tableView.mj_header = header;
    self.tableView.mj_footer = footer;
    
    [self showDataLoadState];
    [self loadDataSource];
}
- (void)registNote{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateQuestionList:) name:@"updateQuestionList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateQuestionTime:) name:@"updateQuestionTime" object:nil];
}
- (void)updateQuestionList:(NSNotification *)note{
    CampusQuestionDetailModel *model = note.userInfo[@"data"];
    CampusSchoolQuestionItemModel *itemModel = [[CampusSchoolQuestionItemModel alloc]init];
    itemModel.id = model.id;
    itemModel.answerCount = @0;
    itemModel.createTime = model.createTime;
    itemModel.question = model.question;
    
    [self.dataArray insertObject:itemModel atIndex:0];
    [self.tableView reloadData];
}


- (void)updateQuestionTime:(NSNotification *)note{
    NSNumber *questionId = note.userInfo[@"data"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = questionId;
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolQuestionDetail];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolQuestionDetail) parames:param success:^(id responseObj) {
        CampusQuestionDetailModel *questionModel = [CampusQuestionDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        __block BOOL isUpdate = NO;
        [self.dataArray enumerateObjectsUsingBlock:^(CampusSchoolQuestionItemModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.id isEqualToNumber:questionModel.id]) {
                obj.createTime = questionModel.createTime;
                isUpdate = YES;
                *stop = YES;
            }
        }];
        
        if (isUpdate) {
            [self.tableView reloadData];
        }
        

    } failure:^(id error) {
        
    }];
}

- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolQuestionList];
    param[@"id"] = self.schId;
    param[@"pageIndex"] = @(self.pageIndex);
    param[@"pageSize"] = @(10);
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolQuestionList) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
        [self stopRefresh];
        if (self.pageIndex == 1) {
            self.dataArray = [CampusSchoolQuestionItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[CampusSchoolQuestionItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        
        CGFloat bottom = self.tableView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE]boolValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }

        }
        
        [self.tableView reloadData];
    } failure:^(id error) {
        [self hideDataLoadLoadState];
        [self stopRefresh];
    }];
    
}
- (void)stopRefresh{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)postMethod{
    
    [self.view endEditing:YES];
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    CampusPostQuestionViewController *vc = [[CampusPostQuestionViewController alloc]init];
    vc.schId = self.schId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CampusQuetionItemCell *cell = [CampusQuetionItemCell cellWithTableView:tableView];
    [cell setItemModel:self.dataArray[indexPath.item]];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (void)showQuestionDetail:(CampusSchoolQuestionItemModel *)itemModel{
    
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = itemModel.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolQuestionDetail];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolQuestionDetail) parames:param success:^(id responseObj) {
        
        [self hideDataLoadLoadState];

        CampusQuestionDetailViewController *vc = [[CampusQuestionDetailViewController alloc]init];
        vc.questionId = itemModel.id;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
    

}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

@end
